/*
 * @Description: 场馆地图绘制
 * @Author: zy
 * @Date: 2021-03-29 15:32:54
 * @LastEditors: zy
 * @LastEditTime: 2021-03-31 09:19:42
 */
import * as d3 from 'd3'

export class VenueCanvas {
  chart = {}

  constructor (divId) {
    this.divId = divId
  }

  initChart () {
    this.chart.padding = {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    }
    this.chart.divHeight = document.getElementById(this.divId).offsetHeight -
      this.chart.padding.top -
      this.chart.padding.bottom
    this.chart.divWidth = document.getElementById(this.divId).offsetWidth -
      this.chart.padding.left -
      this.chart.padding.right

    this.chart.svg = d3
      .select('#' + this.divId)
      .append('svg')
      .attr('width', this.chart.divWidth +
        this.chart.padding.left +
        this.chart.padding.right
      )
      .attr('height', this.chart.divHeight +
        this.chart.padding.top +
        this.chart.padding.bottom
      )
      .attr('class', 'svg_chart')
  }

  initAxis (width, height) {
    this.chart.xScale = d3.scaleLinear()
      .domain([0, width])
      .range([0, this.chart.divWidth])

    this.chart.yScale = d3.scaleLinear()
      .domain([0, height])
      .range([0, this.chart.divHeight])

    this.chart.xAxis = d3.axisTop()
      .scale(this.chart.xScale)
      .ticks(width * 2)

    this.chart.yAxis = d3.axisLeft()
      .scale(this.chart.yScale)
      .ticks(height * 2)

    if (!this.chart.svg.select('.xAxis').empty()) {
      this.chart.svg.select('.xAxis').remove()
    }
    if (!this.chart.svg.select('.yAxis').empty()) {
      this.chart.svg.select('.yAxis').remove()
    }
    this.chart.svg.append('g')
      .attr('class', 'xAxis')
      .call(this.chart.xAxis)
    this.chart.svg.append('g')
      .attr('class', 'yAxis')
      .call(this.chart.yAxis)
    this.renderGrid()
  }

  renderGrid () {
    let chart = this.chart
    chart.svg.selectAll('.grid').remove()
    this.chart.svg.select('.xAxis')
      .selectAll('.tick')
      .each(function (d) {
        d3.select(this).append('line')
          .attr('class', 'grid')
          .attr('x1', chart.xScale(d))
          .attr('y1', 0)
          .attr('x2', chart.xScale(d))
          .attr('y2', chart.divHeight)
          .style('stroke', 'red')
      })
    this.chart.svg.select('.yAxis')
      .selectAll('.tick')
      .each(function (d) {
        d3.select(this).append('line')
          .attr('class', 'grid')
          .attr('x1', 0)
          .attr('y1', chart.yScale(d))
          .attr('x2', chart.divWidth)
          .attr('y2', chart.yScale(d))
          .style('stroke', 'red')
      })
  }
}
